﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AITankActor : TankActor {

    public float detectRange = 6;
    NavMeshAgent agent;

    List<TankActor> enemyList = new List<TankActor>(); //附近玩家的列表


    private Vector3 targetPoint;
	// Use this for initialization
	void Start () {
        this.agent = GetComponent<NavMeshAgent>();
        this.agent.speed = this.tankData.moveSpeed;
        targetPoint = this.transform.position;
        StartCoroutine(DetecedEnemy());
	}

    /// <summary>
    /// 随机附近一个点
    /// </summary>
    /// <param name="center"></param>
    /// <param name="range"></param>
    /// <param name="result"></param>
    private void RandomPoint(Vector3 center, float range, out Vector3 result)
    {
        //clear previous target point
        result = Vector3.zero;

        //try to find a valid point on the navmesh with an upper limit (30 times)
        for (int i = 0; i < 30; i++)
        {
            //find a point in the movement radius
            Vector3 randomPoint = center + (Vector3)Random.insideUnitCircle * range;
            NavMeshHit hit;

            //if the point found is a valid target point, set it and continue
            if (NavMesh.SamplePosition(randomPoint, out hit, 1f, NavMesh.AllAreas))
            {
                result = hit.position;
                break;
            }
        }

        //set the target point as the new destination
        agent.SetDestination(result);
        
    }

    /// <summary>
    /// 检测附近的玩家
    /// </summary>
    /// <returns></returns>
    IEnumerator DetecedEnemy()
    {
        yield return new WaitForSeconds(2f);
        while (true)
        {
            enemyList.Clear();
            var coliders =  Physics.OverlapSphere(this.transform.position, detectRange, LayerMask.GetMask("Player"));
            foreach(var col in coliders)
            {
                var actor = col.GetComponent<TankActor>();
                if (actor != null && actor.ActorInfo.actorGUID != this.ActorInfo.actorGUID)
                {
                    enemyList.Add(actor);
                }
                  
            }

            yield return new WaitForSeconds(1f);
        }
    }
    private void FixedUpdate()
    {
        

        if(enemyList.Count == 0)
        {

            if (Vector3.Distance(transform.position, targetPoint) < agent.stoppingDistance)
            {
                RandomPoint(transform.position, detectRange * 3, out targetPoint);
            }
        }
        else
        {
            if (Vector3.Distance(transform.position, targetPoint) <= agent.stoppingDistance)
            {
                RandomPoint(enemyList[0].transform.position, detectRange * 1.5f, out targetPoint);
            }

        }

        //shooting loop 
        for (int i = 0; i < enemyList.Count; i++)
        {
            RaycastHit hit;
            //raycast to detect visible enemies and shoot at their current position
            if (Physics.Linecast(transform.position, enemyList[i].transform.position, out hit))
            {
                //get current enemy position and rotate this turret
                Vector3 lookPos = enemyList[i].transform.position;
                Turret.transform.LookAt(lookPos);
                Turret.transform.eulerAngles = new Vector3(0, Turret.transform.eulerAngles.y, 0);

                //find shot direction and shoot there
                Vector3 shotDir = lookPos - transform.position;
                //Shoot(new Vector2(shotDir.x, shotDir.z));
                Shooting();
                break;
            }
        }
    }

}
